import { Component, OnInit, Input } from '@angular/core';
import { environment } from '@env/environment';
import { _HttpClient } from '@delon/theme';
import { DomSanitizer } from '@angular/platform-browser';
import { LocalStorage } from '@core/local.storage';
import { TreeTools } from '@core/treeTools.tool';
import { DatePipe } from '@angular/common';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { ApiService } from '@core/api.service';
import { ControlApiService } from '@core/controlApi.service';
import { WeekWorkService } from './weekwork.service';


@Component({
    selector: 'app-weekwork-detail',
    templateUrl: './weekwork.detail.component.html',
    styleUrls: ['./weekwork.component.less'],
})
export class WeekworkDetailComponent implements OnInit {
    tableData = [];
    dateTh = [];
    lockHeadScroll = { x: '2500px', y: window.innerHeight - 350 + 'px' };
    iframeSrc;
    tableData_mx = [];
    detailVisible = false;
    detailMode = 'detail';
    editable = false;
    deleteable = false;
    addable = false;

    pageIndex: any = 1;
    pageSize = '50';
    pageTotal: any = '';

    editData: any = {};
    detailData: any = {};
    nzOkText = "";
    detialTitle: string;
    userInfo = JSON.parse(this.ls.get('loginInfo'));
    zyList = [];

    dropdownStyle = { height: '150px', width: 'auto' };
    nid: any;
    dtWsdate
    czList = [];
    lineList = [];
    jhrqDates = [];
    selectedJhrq = [];
    shebeiList = [];
    orgType: any;
    private _inputParam: any = {};
    zydwList: any[] = [];

    tc_sdStatus = { // 天窗、上道 状态
        '0': '需要', '1': '不需要',
    };

    lvlList = {
        '0': '一级',
        '1': '二级',
        '2': '三级',
        '3': '四级',
    }

    @Input()
    set inputParam(v) {
        this._inputParam = v;
        if (v.nId) {
            this.query_mx({ mid: v.nId });
            this.nid = v.nId;
        }
        this.orgType = v.orgType;
        this.editable = v._editable || false;
        this.deleteable = v._deleteable || false;
        this.addable = v._addable || false;
        this.initEditData();
        this.getZydwList();
    };

    constructor(
        private http: _HttpClient,
        public sanitizer: DomSanitizer,
        private ls: LocalStorage,
        private treeTools: TreeTools,
        private datePipe: DatePipe,
        private message: NzMessageService,
        private apiService: ApiService,
        private controlApiService: ControlApiService,
        private weekWorkService: WeekWorkService,
        private modalService: NzModalService,
    ) { }

    ngOnInit(): void {
        this.initZyxm();
        this.getCz(this.userInfo.VC_ORG$ID);
        this.getXingbie();
        this.initJhrqDates();

    }

    initEditData() {
        this.editData.orgname = this._inputParam.vcOrgName;
        this.editData.orgid = this._inputParam.vcOrg$id;
    }

    initJhrqDates() {
        this.jhrqDates = []
        const _today = new Date();
        const day = _today.getDay();
        const _date = _today.getDate();
        const r = _date - day;
        const weektitle = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        weektitle.forEach((title, index) => {
            const loopDate = index + 1 + r;
            const dateStr = this.datePipe.transform(_today.setDate(loopDate), 'yyyy-MM-dd');
            this.jhrqDates.push({
                title,
                value: dateStr
            });
        });
    }

    /**
     * place 
     * 工区 - "00"
     * 车间 - "01"
     * 段 - "02"
     */
    initZyxm() {
        const param: any = {};
        const tab = this._inputParam._tab;
        if (tab.includes('gq')) {
            param.place = '00';
        } else if (tab.includes('cj')) {
            param.place = '01';
        } else {
            param.place = '02';
        }
        const url = environment.apiBase + '/csmis/jxProjects/getAllJxProjects.jwt';
        this.http.get(url, param).subscribe(res => {
            this.treeTools.formatTreeNodes({
                nodes: res,
            })
            this.treeTools.loopTree({
                nodes: res,
                logicArr: [{
                    judgeFunc: (node) => {
                        node.selectable = node.children && node.children.length ? false : true;
                    }
                }]
            })
            this.zyList = res;

        });
    }
    /**
     * pnid 取所选记录N_ID
     */
    query_mx(param) {
        if (!param.page) {
            param.page = this.pageIndex;
        }
        if (!param.limit) {
            param.limit = this.pageSize;
        }
        if (!param.mid) {
            param.mid = this.nid;
        }
        const url = environment.project + '/ymTWeekPlan/query';
        this.http.get(url, param).subscribe(res => {
            this.tableData_mx = res.data;
            this.pageTotal = res.count;
        });

    }

    checkAll(v) {
        this.tableData_mx.forEach(row => {
            row.checked = v;
        });
    }

    pageSizeChange(v) {
        this.pageSize = v;
        this.query_mx({});
    }

    pageIndexChange(v) {
        this.pageIndex = v;
        this.query_mx({});
    }

    trDbclick(_row) {
        const row = JSON.parse(JSON.stringify(_row));
        this.editData = {};

        const textCfg = {
            title: {
                add: '新增',
                edit: '修改',
                detail: '明细',
            },
            btnOkText: {
                add: '新增',
                edit: '保存',
                detail: '确定',
            }
        }
        this.detailMode = this.editable === true ? 'edit' : 'detail';
        this.nzOkText = textCfg.btnOkText[this.detailMode];
        this.detialTitle = textCfg.title[this.detailMode];
        this.detailVisible = true;

        if (this.detailMode === 'detail') {
            this.detailData = row;
        } else {
            // 获取设备列表
            this.apiService.equipmentData(row.station, row.devtypeid, '', '').subscribe((res: any) => {
                if (res.type === 'success') {
                    this.shebeiList = res.data.pageList;
                    this.str2Date(row);
                    this.str2Arr(row);
                    this.editData = row;
                    this.initEditData();
                    this.editData.plandate = row.workdate || '';
                    this.zyxmChange(row.projectid);
                }
            });
        }

    }

    addModal() {
        this.detailMode = 'add';
        this.nzOkText = '新增';
        this.detialTitle = '新增';
        this.detailVisible = true;

        if (this.orgType === '1') {
            this.editData = {
                orgname: this.userInfo.VC_ORG$NAME,
                orgid: this.userInfo.VC_ORG$ID
            };
        } else {
            this.editData = {};
        }
    }


    getChecked() {
        const delRows = this.tableData_mx.filter(row => row.checked);
        return delRows;
    }

    delAll() {
        const checkedRows = this.getChecked();
        if (!checkedRows.length) {
            this.message.warning('请勾选一条记录进行操作');
            return;
        }
        this.modalService.confirm({
            nzTitle: `确认删除勾选项？`,
            nzWidth: '600',
            nzOnOk: () => {
                const ids = [];
                checkedRows.forEach(row => {
                    ids.push(row.id);
                });
                const url = environment.project + '/ymTWeekPlan/deleteBatch';
                this.http.post(url, ids).subscribe(res => { 
                    if (res.msg === 'Ok') {
                        this.message.success('删除成功')
                        this.query_mx({});
                    } else {
                        this.message.success('删除失败')

                    }

                })
            }
        })

    }

    detailCancel() {
        this.detailVisible = false;
    }

    fieldCheck(param) {
        let res = true;
        if (!param.begintime) {
            this.message.warning('请填写开始时间');
            res = false
        }
        if (!param.endtime) {
            this.message.warning('请填写结束时间');
            res = false
        }
        if (!param.plandate) {
            this.message.warning('请填写计划日期');
            res = false
        }
        if (!param.orgid) {
            this.message.warning('请填写作业单位');
            res = false
        }

        return res;
    }
    date2Str(param) {
        param.begintime = param._begintime ? this.datePipe.transform(param._begintime, 'HH:mm') : '';
        param.endtime = param._endtime ? this.datePipe.transform(param._endtime, 'HH:mm') : '';

    }
    arr2Str(param) {
        param.devid = param._devids ? param._devids.join() : '';
        if (param._orgid) {
            param.orgid = param._orgid.join();
        }
    }
    str2Date(row) {
        if (row.begintime) {
            const times = row.begintime.split(':');
            const _date = new Date();
            _date.setHours(times[0]);
            _date.setMinutes(times[1]);
            row._begintime = _date;
        }
        if (row.endtime) {
            const times = row.endtime.split(':');
            const _date = new Date();
            _date.setHours(times[0]);
            _date.setMinutes(times[1]);
            row._endtime = _date;
        }
    }
    str2Arr(row) {
        if (row.devid) {
            row._devids = row.devid.split(',');
            row.devname = "";
        }
        if (row.orgid && row.orgid.length) {
            row._orgid = row.orgid.split(',');
            row.orgname = "";
        }
    }
    /**
     * 删除私立字段
     * @param param 参数
     */
    removePrivateFields(param) {
        Object.keys(param).forEach(key => {
            if (!(key.indexOf('_'))) {
                delete param[key];
            }
        });
    }

    setFieldNames(param) {
        if (param._orgid && this.zydwList.length) {
            param.orgname = this.treeTools.getNodeNames({
                nodes: this.zydwList,
                ids: param._orgid,
                keyName: 'opValue',
                valueName: 'opName',
            })
        }
        if (param.devid) {
            param.devname = this.treeTools.getNodeNames({
                nodes: this.shebeiList,
                ids: param.devid,
                keyName: 'opValue',
                valueName: 'opName',
            })
        }
        if (param.station) {
            param.stationname = this.treeTools.getTreeNodeName({
                nodes: this.czList,
                id: param.station,
            })
        }
        if (param.line) {
            param.linename = this.treeTools.getTreeNodeName({
                nodes: this.lineList,
                id: param.line,
            })
        }
        if (param.projectid) {
            param.projectname = this.treeTools.getTreeNodeName({
                nodes: this.zyList,
                id: param.projectid
            })
        }
    }

    detailOk() {
        const param = {
            mid: this.nid
        }
        Object.assign(param, this.editData)
        this.date2Str(param);
        this.arr2Str(param);
        this.setFieldNames(param);
        this.removePrivateFields(param);
        const data = this.fieldCheck(param);
        if (!data) {
            return;
        }
        let url;
        if (this.detailMode === 'add') {
            url = environment.project + '/ymTWeekPlan/add';
        } else if (this.detailMode === 'edit') {
            url = environment.project + '/ymTWeekPlan/update';
        }
        this.http.post(url, param).subscribe(res => {
            const optType = this.detailMode === 'add' ? '新增' : "保存";
            if (res.msg === 'Ok') {
                this.message.success(optType + '成功');
                this.query_mx({ mid: this.nid })
                this.detailVisible = false;
            } else {
                this.message.error(optType + '失败');
            }
        });
    }

    getShebei(id) {
        const url = environment.apiBase + '/csmis/jxProjects/findOne.jwt';
        this.http.get(url, { id }).subscribe(res => {
            const data = res[0];
            this.editData._lvl = data.LEVELNAME;// 等级
            this.editData.lvl = data.VCLEVEL;// 等级
            this.editData.devtypename = data.DEVTYPELEVEL;// 设备类型
            this.editData.devtypeid = data.DEVTYPE;// 设备类型编号
            this.editData.projecttype = data.TYPENAME;// 作业类型 
            if (this.editData.station) {
                this.getShebeiList(this.editData.station, this.editData.devtypeid);
            }
        });
    }

    getShebeiList(staid, devtype) {
        this.apiService.equipmentData(staid, devtype, '', '').subscribe((res: any) => {
            if (res.type === 'success') {
                this.shebeiList = res.data.pageList;
            }
        });
    }

    zyxmChange(v) {
        if (v) {
            this.getShebei(v);
        }
    }

    czChange(v) {
        if (this.editData.devtypeid && v) {
            this.editData.station = v;
            this.getShebeiList(v, this.editData.devtypeid);
        }
    }

    getCz(orgid) {
        if (orgid === 'KMBUR_KMNSEG_ORG_38') {
            orgid = '';
        }
        this.weekWorkService.getStationByOrgId(orgid, '0').subscribe(res => {
            this.treeTools.formatTreeNodes({
                nodes: res,
                selectOnlyLeaf: true
            });
            this.czList = res;
        })
    }

    getXingbie() {
        this.controlApiService.getAllLines().subscribe((res: any) => {
            if (res.length) {
                this.treeTools.formatTreeNodes({
                    nodes: res,
                    keyName: 'opValue',
                    valueName: 'opName',
                });
                this.lineList = res;
            }
        });
    }

    getZydwList() {
        let ob;
        switch (this.orgType) {
            case '2': // 车间
                const param = {
                    yesorno: '0',
                    orgId: this._inputParam.vcOrg$id
                }
                ob = this.weekWorkService.getgongquByCjId(param);
                break;
            case '3': // 技术科
                ob = this.weekWorkService.getCjList();
                break;
            default:
                break;
        }
        if (ob) {
            ob.subscribe(res => {
                this.zydwList = res;
            })
        }
    }

    disabledDate(v) {
        return true;
    }

    addJhrq(content) {
        this.selectedJhrq = [];
        this.modalService.info({
            nzTitle: '选择日期',
            nzContent: content,
            nzWidth: '60vw',
            nzOkText: '确定',
            nzCancelText: '取消',
            nzOnOk: () => {
                this.editData.plandate = this.selectedJhrq.join();
            }
        });
    }

    selectJhrq(v) {
        if (v) {
            if (this.selectedJhrq.includes(v)) {
                return;
            }
            this.selectedJhrq.push(v);
        }

    }
}